package com.wen.common.interceptor;

import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;

/**
 * mybatis 拦截器
 * <p>
 * 拦截由@Signature标记的一些方法，比如对SQL语句进行格式化
 *
 * <p>
 * 拦截器的作用是，在执行目标方法之前，对参数进行一些处理（比如格式化、加密等），
 * 在执行目标方法之后，对返回结果进行一些处理（比如解密、脱敏等），
 * 从而实现对目标方法的增强。
 * </p>
 *
 * @author devin <devinlive@163.com>
 * @version 1.0
 * @since 2024/6/11 17:06
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}),
//        @Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
//        @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
//        @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})
})
public class SqlInterceptor implements Interceptor {

    private static final Logger log = LoggerFactory.getLogger(SqlInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取到StatementHandler
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        // 获取到ParameterHandler
        ParameterHandler parameterHandler = statementHandler.getParameterHandler();

        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
//        ParameterHandler parameterHandler1 = (ParameterHandler) metaObject.getValue("delegate.parameterHandler");
        // 获取到Configuration
        Configuration configuration = (Configuration) metaObject.getValue("delegate.configuration");

        log.info("invocation target : {}", invocation.getTarget());
        log.info("invocation method : {}", invocation.getMethod());

        // 获取SQL语句
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();
        // 获取参数
        Object parameterObject = boundSql.getParameterObject();

        // 打印SQL语句
        System.out.println("*** Executing SQL: " + sql);
        System.out.println("*** Parameters: " + parameterObject.toString());
        System.out.println("*** Parameters: " + parameterHandler.getParameterObject());

        Object arg = invocation.getArgs()[0];
        log.info("invocation args : {}", arg);
        // 替换占位符
        String completeSql = showSql(configuration, boundSql);

        System.out.println("*** Complete SQL: " + completeSql);
        // 继续执行
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }


    private String showSql(Configuration configuration, BoundSql boundSql) {
        // 获取参数映射
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();

        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (!parameterMappings.isEmpty() && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    }
                }
            }
        }
        return sql;
    }

    private String getParameterValue(Object obj) {
        String value;
        if (obj instanceof String) {
            value = "'" + obj + "'";
        } else if (obj instanceof Date) {
            value = "'" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(obj) + "'";
        } else {
            value = obj != null ? obj.toString() : "";
        }
        return value;
    }
}